from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from app.services.point_service import (
    get_shop_points,
    recharge_points,
    get_transaction_history
)
from app.services.point_calculator_service import calculate_translation_points
from app.utils.response_handler import SuccessResponse
import logging
import traceback

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
router = APIRouter(prefix="/api/v1")


# 积分充值请求模型
class RechargeRequest(BaseModel):
    shop_domain: str = Field(..., description="店铺域名")
    points: int = Field(..., gt=0, description="充值积分数量")
    description: str = Field("Shopify支付充值", description="充值描述")


# 查询积分请求模型
class PointsQueryRequest(BaseModel):
    shop_domain: str = Field(..., description="店铺域名")


# 积分计算请求模型
class PointsCalculateRequest(BaseModel):
    text: str = Field(..., description="需要计算积分的文本内容")


# 获取积分接口
@router.post("/points/balance", response_model=SuccessResponse)
async def get_points_balance(req_data: PointsQueryRequest):
    """获取店铺当前积分余额"""
    try:
        logging.info(f"查询积分请求: 店铺={req_data.shop_domain}")
        
        # 获取积分
        points = get_shop_points(req_data.shop_domain)
        
        response_data = {
            "shop_domain": req_data.shop_domain,
            "total_points": points
        }
        
        logging.info(f"查询积分结果: {response_data}")
        return SuccessResponse(data=response_data)
        
    except Exception as e:
        logging.error(f"查询积分失败: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


# 积分充值接口
@router.post("/points/recharge", response_model=SuccessResponse)
async def recharge_points_endpoint(req_data: RechargeRequest):
    """
    积分充值接口
    用于处理Shopify支付成功后的积分充值
    """
    try:
        logging.info(
            f"充值积分请求: 店铺={req_data.shop_domain}, 积分={req_data.points}, 描述={req_data.description}"
        )
        
        # 执行充值
        success, message = recharge_points(
            shop_domain=req_data.shop_domain,
            points=req_data.points,
            description=req_data.description,
            related_service="shopify_payment"
        )
        
        if not success:
            logging.error(f"充值失败: {message}")
            raise HTTPException(
                status_code=400,
                detail=message
            )
        
        # 获取充值后的余额
        current_balance = get_shop_points(req_data.shop_domain)
        
        response_data = {
            "shop_domain": req_data.shop_domain,
            "recharged_points": req_data.points,
            "current_balance": current_balance,
            "message": message
        }
        
        logging.info(f"充值成功: {response_data}")
        return SuccessResponse(data=response_data)
        
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"充值积分异常: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


# 获取交易历史接口
@router.get("/points/history", response_model=SuccessResponse)
async def get_points_history(
    shop_domain: str = Query(..., description="店铺域名"),
    limit: int = Query(50, ge=1, le=100, description="返回记录数量"),
    offset: int = Query(0, ge=0, description="偏移量")
):
    """获取积分交易历史记录"""
    try:
        logging.info(
            f"获取交易历史请求: 店铺={shop_domain}, 限制={limit}, 偏移={offset}"
        )
        
        # 获取交易历史
        history = get_transaction_history(shop_domain, limit, offset)
        
        response_data = {
            "shop_domain": shop_domain,
            "total_records": len(history),
            "limit": limit,
            "offset": offset,
            "transactions": history
        }
        
        logging.info(f"获取交易历史成功: 记录数={len(history)}")
        return SuccessResponse(data=response_data)
        
    except Exception as e:
        logging.error(f"获取交易历史失败: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


# 积分计算接口
@router.post("/points/calculate", response_model=SuccessResponse)
async def calculate_points(req_data: PointsCalculateRequest):
    """
    积分计算接口
    用于计算指定文本翻译所需的积分
    """
    try:
        logging.info(f"积分计算请求: 文本长度={len(req_data.text)}")
        
        # 计算所需积分
        char_count = len(req_data.text)
        points_needed = calculate_translation_points(req_data.text)
        
        response_data = {
            "char_count": char_count,
            "points_needed": points_needed,
            "calculation_rule": "每10个字符1积分"
        }
        
        logging.info(f"积分计算结果: {response_data}")
        return SuccessResponse(data=response_data)
        
    except Exception as e:
        logging.error(f"积分计算失败: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )